const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router(); // router 对象相当于是一个小型的 app 对象
const UserModel = require("../db/models/UserModel");
const md5 = require("md5");
const { createToken } = require("../utils/token");

//为 router 对象设置 bodyParser 中间件
// parse application/x-www-form-urlencoded
router.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
router.use(bodyParser.json());

//登录
router.post("/login", async (req, res) => {
  //获取用户填写的账号和密码
  // console.log(req.body);
  try {
    //查询数据库中, 是否有匹配的数据
    let user = await UserModel.findOne({
      uname: req.body.uname,
      pwd: md5(req.body.pwd),
    });
    //数据库找不到数据的情况
    if (!user) {
      return res.json({
        msg: "用户名或密码错误",
        code: "1005",
        data: null,
      });
    }
    //生成 token 字符串
    let token = createToken({
      uid: user._id,
      uname: user.uname,
    });
    res.json({
      msg: "登录成功",
      code: "0000",
      data: {
        token: token,
      },
    });
  } catch (e) {
    console.log('运行异常');
    res.json({
      msg: '运行异常',
      code: '2002',
      data: null
    })
  }
});

//注册
router.post('/reg', (req, res)=>{

})

//退出登录   这里不需要后端即可完成登录功能
router.delete("/logout", (req, res) => {
  res.send("退出登录");
});

module.exports = router;
